package mongo

import (
	"context"
	"gitee.com/xiedongji/antgo/cpts/xlog"
	"gitee.com/xiedongji/antgo/helper/xstring"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"go.mongodb.org/mongo-driver/mongo/readpref"
	"time"
)

/* ============================================================ *
 * 功能: redis
 * 说明：可以连接中uri中写入密码
 * 		例: mongodb://user:password@localhost:27017
 *  	也可以独立设置账号密码
 * ============================================================ */
const cptName = "mongo"

var instance *Instance
var _client *mongo.Client

type Instance struct {
	MongoUri       string `yaml:"uri"`
	Username       string `yaml:"username"`
	Password       string `yaml:"password"`
	ConnectTimeout int64  `yaml:"connect_timeout"`
}

func (i *Instance) GetName() string {
	return cptName
}

func (i *Instance) Run() (err error) {
	instance = i

	iOptions := options.Client().ApplyURI(i.MongoUri).SetConnectTimeout(time.Duration(i.ConnectTimeout))
	if !xstring.IsEmpty(i.Username) && !xstring.IsEmpty(i.Password) {
		iOptions = iOptions.SetAuth(options.Credential{
			Username: i.Username,
			Password: i.Password,
		})
	}

	if _client, err = mongo.Connect(context.TODO(), iOptions); err != nil {
		return err
	}

	if err = _client.Ping(context.TODO(), readpref.Primary()); err != nil {
		return err
	}

	return nil
}

// ====================== 业务板块 ======================
func GetClient() *mongo.Client {
	if _client == nil {
		xlog.Logger(cptName, "Mongo").Info().Msg("获取 mongo client 为空")
	}
	return _client
}
